package com.ljph.jfinal.base;

import com.jfinal.core.Controller;
import com.jfinal.json.Json;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by yuzhou on 16/8/4.
 */
public class BaseController extends Controller {

    public static String SUCCESS_KEY = "ok";
    public static String ERROR_KEY = "msg";

    protected void commonSuccessJson() {
        Map<String, Object> json = new HashMap<String, Object>();
        json.put(SUCCESS_KEY, true);
        renderJson(json);
    }

    protected void commonSuccessJson(Json json, String key, Object data) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ok", true);
        map.put(key, data);

        if(json == null) {
            renderJson(map);
        } else {
            renderJson(json.toJson(map));
        }
    }

    protected void commonSuccessJson(String key, Object data) {
        commonSuccessJson(null, key, data);
    }


    protected void commonSuccessJson(Json json, Map<String, Object> dataMap) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(SUCCESS_KEY, true);

        dataMap.keySet().forEach(key -> {
            map.put(key.toString(), dataMap.get(key));
        });

        if(json == null) {
            renderJson(map);
        } else {
            renderJson(json.toJson(map));
        }
    }

    protected void commonSuccessJson(Map<String, Object> dataMap) {
        commonSuccessJson((Json)null, dataMap);
    }

    public void commonFailJson(String msg) {
        Map<String, Object> json = new HashMap<String, Object>();
        json.put(SUCCESS_KEY, false);
        json.put(ERROR_KEY, msg);
        renderJson(json);
    }
}
